package com.ccb.sc.setting.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ccb.sc.setting.vo.AdPositionVo;
import com.ccb.sc.common.bind.response.ResBody;
import com.ccb.sc.common.enums.ValidStatus;
import com.ccb.sc.common.modules.ad.entity.Ad;
import com.ccb.sc.common.modules.ad.entity.AdPosition;
import com.ccb.sc.common.modules.ad.service.IAdPositionService;
import com.ccb.sc.common.modules.ad.service.IAdService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ken
 * @version 1.0
 * @date 2020-10-06
 */
@RestController
@RequestMapping("/app/ad")
@Api(value = "广告位管理", tags = "广告位管理")
public class AppAdController {

    private IAdPositionService adPositionService;
    private IAdService adService;

    @GetMapping
    @ApiOperation(value = "获取广告位内容", response = AdPositionVo.class)
    public ResBody<?> getAd(@RequestParam String code) {
        Assert.notNull(code, "code cannot null");
        AdPosition adPosition = this.adPositionService.findByCode(code);
        if (adPosition == null || ValidStatus.INVALID.equals(adPosition.getStatus())) {
            return ResBody.success();
        }
        AdPositionVo vo = new AdPositionVo();
        vo.setCode(adPosition.getCode());
        vo.setWidth(adPosition.getWidth());
        vo.setHeight(adPosition.getHeight());
        List<Ad> ads = this.adService.list(new QueryWrapper<Ad>()
                .lambda()
                .eq(Ad::getAdPositionId, adPosition.getId())
                .eq(Ad::getStatus, ValidStatus.VALID)
                .orderByAsc(Ad::getOrders));
        if (!CollectionUtils.isEmpty(ads)) {
            ads = ads.stream().filter(item -> {
                boolean filter = (item.getStartTime() != null && item.getStartTime().isAfter(LocalDateTime.now()))
                        || (item.getEndTime() != null && item.getEndTime().isBefore(LocalDateTime.now()));
                return !filter;
            }).collect(Collectors.toList());
            vo.setAds(ads);
        }
        return ResBody.success(vo);
    }

    @Autowired
    public void setAdPositionService(IAdPositionService adPositionService) {
        this.adPositionService = adPositionService;
    }

    @Autowired
    public void setAdService(IAdService adService) {
        this.adService = adService;
    }
}
